//
//  XQHomeController.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/3.
//

import UIKit

class XQHomeController: UIViewController {
    
    private var currentViewController: XQBaseCardController?
    
    private var firstLoad : Bool = false
    
    private var homeModel : XQHomeModel?
    
    private lazy var hasApplyClicked = false
    
    private var topCardInfo : XQHomeReadingCaucasianModel?
    
    private lazy var bgImageView : UIImageView = {
        let ima = UIImageView()
        ima.image = UIImage(named: "bg_home")
        ima.isUserInteractionEnabled = true
        return ima
    }()
    
    private lazy var topView : XQHomeNavBar = {
        let topView = XQHomeNavBar()
        topView.customerHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.customerClick()
        }
        return topView
    }()
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = .clear
        self.makeUI()
        self.makeConstraints()
        self.initObserver()
                
        self.initBattery()
        
        XQHud.showLoading(controller: self)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        refreshData()
        needCheckLocation()
    }
    
    func makeUI() {
        self.view.addSubview(self.bgImageView)
        self.view.addSubview(self.topView)
    }
    
    func makeConstraints() {
        self.bgImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.topView.snp.makeConstraints { make in
            make.top.equalTo(UIDevice.xq_statusHeight() + 11)
            make.left.equalTo(10)
            make.right.equalTo(-15)
            make.height.equalTo(48)
        }
    }
    
    private func refreshData() {
        XQNetworkManager.shared.getRequest(url: "/figures/performing") {[weak self] response, error in
            guard let srongify = self else {return}
            XQHud.hideLoading(controller: srongify)
            srongify.endRefreshing()
            
            if (response?.object == 0)  {
                
                if let model = XQHomeModel.deserialize(from: response?.procedure) {
                    srongify.homeModel = model
                    
                    srongify.updateData()
                    
                    srongify.notifyData()
                }
            }
        }
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    private func updateData() {
        self.updateCustomer()
        self.updatePageData();
    }
    
    private func updateCustomer() {
        self.topView.customerImageName = self.homeModel?.repeatable?.precise
    }
    
    private func getTopCardInfo(topCardArray : [XQHomeReadingCaucasianModel]?) {
        if let topList = topCardArray {
            if (topList.count != 0) {
                topCardInfo = topList.first
                updateNav()
                self.currentViewController?.topCardInfo = topCardInfo
                self.currentViewController?.repeatableModel = self.homeModel?.repeatable
            }
        }
    }
    
    private func getListDataSource(list : [XQHomeReadingCaucasianModel]) {
        self.currentViewController?.listDataSource = list
    }
    
    private func updateNav() {
        self.topView.title = self.topCardInfo?.flashlight
        self.topView.logo = self.topCardInfo?.coarseness
    }
    
    private func applyClick() {
        if !hasApplyClicked {
            hasApplyClicked = true
            checkValideOrderId(orderId:self.topCardInfo?.order)
        }
    }
        
    private func needCheckLocation() {
        if !firstLoad {
            firstLoad = true
            XQLocationTool.checkLocationAuthorization(controller: self)
        }
    }
    
    private func customerClick() {
        guard let url = self.homeModel?.repeatable?.respondents else {return}
        
        if !url.isEmpty {
            XQRouteTool.jumpController(controller: self, url: url)
        }
    }
    
    private func switchToLargeCard() {
        let vc = XQLargeCardController()
        vc.refreshHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.refreshData()
        }
        vc.applyHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.applyClick()
        }
        switchViewController(to: vc)
    }
    
    private func switchToSmallCard() {
        let vc = XQSmallCardController()
        vc.refreshHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.refreshData()
        }
        vc.applyHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.applyClick()
        }
        vc.didSelectHandle = {[weak self] str in
            guard let srongify = self else {return}
            srongify.checkValideOrderId(orderId: str)
        }
        switchViewController(to: vc)
    }
    
    private func switchViewController(to newViewController: XQBaseCardController) {
        if let currentVC = currentViewController {
            currentVC.willMove(toParent: nil)
            currentVC.view.removeFromSuperview()
            currentVC.removeFromParent()
        }
        
        currentViewController = newViewController
        addChild(newViewController)
        view.addSubview(newViewController.view)
        newViewController.view.frame = CGRectMake(0, UIDevice.xq_statusHeight() + 63, UIDevice.xq_width(), UIDevice.xq_height() - (UIDevice.xq_statusHeight() + 63))
        newViewController.didMove(toParent: self)
    }
    
    private func endRefreshing() {
        if self.currentViewController is XQLargeCardController {
            (self.currentViewController as! XQLargeCardController).endRefreshing()
        }else if self.currentViewController is XQSmallCardController {
            (self.currentViewController as! XQSmallCardController).endRefreshing()
        }
    }
    
    private func notifyData() {
        let manager = XQAnalysisManager.shared
        manager.notifyIdfvAndIdfa()
        manager.notifyDevice()
    }
}
 
extension XQHomeController {
    
    private func checkValideOrderId(orderId : Int?) {
        guard let orId = orderId else {return}
        
        let params : [String : String] = ["taxes" : "\(orId)"]
        
        XQHud.showLoading(controller: self)
        XQNetworkManager.shared.postRequest(url: "/figures/technicians", parameters: params) {[weak self] response, error in
            guard let srongify = self else {return}
            XQHud.hideLoading(controller: srongify)
            srongify.hasApplyClicked = false
            if (response?.object == -2) {
                XQRouteTool.jumpLogin()
            }else {
                if let procedure = response?.procedure {
                    if let url = procedure["measured"] {
                        XQRouteTool.jumpController(controller: srongify, url: url as! String)
                    }
                }
            }
        }
        
    }
    
    private func updatePageData() {
        if let dataSource = self.homeModel?.readings {
            
            var showLarge : Bool = true
            
            var topCardArray : [XQHomeReadingCaucasianModel]?
            
            var list : [XQHomeReadingCaucasianModel]?
            
            for model in dataSource {
                if (model.spectrophotometer == "sharea") {
                    
                }else if (model.spectrophotometer == "shareb") {
                    showLarge = true
                    topCardArray = model.caucasian
                }else if (model.spectrophotometer == "sharec") {
                    showLarge = false
                    topCardArray = model.caucasian
                }else if (model.spectrophotometer == "shared") {
                    list = model.caucasian
                }
            }
             
            if (showLarge) {
                switchToLargeCard()
            }else {
                switchToSmallCard()
            }
            
            getTopCardInfo(topCardArray: topCardArray)
            
            if (list != nil && list?.count != 0) {
                getListDataSource(list: list!)
            }
        }
    }
}

extension XQHomeController {
    
    private func initBattery() {
        UIDevice.current.isBatteryMonitoringEnabled = true
        getBatteryInfo()
        initObserver()
    }
    
    private func initObserver() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(batteryStateDidChange),
            name: UIDevice.batteryStateDidChangeNotification,
            object: nil)
    }
    
    @objc func batteryStateDidChange(notification: Notification) {
       getBatteryInfo()
   }
    
    private func getBatteryInfo() {
        XQBatteryTool.getBatteryInfo()
    }
}
 
